package com.webbei.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;

public class FileUtil {
	
	/**
	 * 文件上传
	 * @param file 
	 * @param path 保存相对路径(按照日期)
	 * @param fileName 文件名
	 * @return
	 */
	public static String upload(File file,String path,String fileName){
		String savePath = "";
		try {
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
			String realDir = ServletActionContext.getServletContext().getRealPath(path);
			File f = new File(realDir);
			if(!f.exists()){
				f.mkdirs();
			}
			
			String saveRealPath = realDir+"/"+fileName;
			savePath = path+"/"+fileName;
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveRealPath));
			byte[]bytes = new byte[1024];
			int i = bis.read(bytes, 0, bytes.length);
			while(i!=-1){
				bos.write(bytes);
				i = bis.read(bytes,0,bytes.length);
			}
			bos.close();
			bos.flush();
			bis.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return savePath;
	}
	/**
	 * 文件删除
	 * @param filePath 文件相对路径
	 * @return ture表示删除了一个文件
	 */
	public static boolean delete(String filePath){
		String real = ServletActionContext.getServletContext().getRealPath("/");
		String deleteRealPath = real+filePath;
		File file = new File(deleteRealPath);
		if(file.exists()){
			return file.delete();
		}
		return false;
	}
	public static boolean isExist(String filePath){
		String real = ServletActionContext.getServletContext().getRealPath("/");
		String deleteRealPath = real+filePath;
		File file = new File(deleteRealPath);
		return file.exists();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
